package com.wf.DouDiZhuOL.Tools;

import com.wf.DouDiZhuOL.proto.GameModule.PBToast;
import com.wf.DouDiZhuOL.util.Constants;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

public class Tools {
	
	public static byte[] strToByteArray(String _str) 
	{
		String[] strings = _str.split(",");
		
		byte[] newBytes = new byte[strings.length];
		for(int i= 0; i < strings.length; i++) 
		{
			newBytes[i] = (byte) Integer.parseInt(strings[i]);
		}
		return newBytes;
	}
	
	public static String byteArrayToStr(byte[] _byteArray) 
	{
		String string = "";
		for(int i= 0; i < _byteArray.length - 1; i++) 
		{
			string += _byteArray[i] + ",";
		}
		string += _byteArray[_byteArray.length - 1];
		return string;
	}
	
	public static ByteBuf getParams(int _type, String _data)
	{
		String params = Constants.REQ_TYPE + "=" + _type;
		if(_data != null && !_data.equals("")) 
		{
			params += ("&" + Constants.REQ_DATA + "=" + _data);
		}
		return Unpooled.copiedBuffer(params, CharsetUtil.UTF_8);
	}
	
	public static void writeToastMsg(ChannelHandlerContext _ctx, int _type, String _msg) 
	{
		PBToast.Builder pbToastBuilder = PBToast.newBuilder();
		pbToastBuilder.setType(_type);
		pbToastBuilder.setMsg(_msg);
		
		PBToast pbToast = pbToastBuilder.build();
		
		ByteBuf params = Tools.getParams(Constants.REQ_TYPE_TOAST, Tools.byteArrayToStr(pbToast.toByteArray()));
		Tools.writeResponse(_ctx, HttpResponseStatus.OK, params);
	}
	
	public static void writeResponse(ChannelHandlerContext _ctx, HttpResponseStatus _status, ByteBuf _content) 
	{
		if(_ctx.channel().isWritable()) 
		{
			FullHttpResponse msg = null;
			if (_content != null) 
			{
				msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, _status, _content);
				msg.headers().set("Access-Control-Allow-Origin", "*");
				msg.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
			} 
			else
			{
				msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, _status);
			}
			if (msg.content() != null) 
			{
				msg.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg.content().readableBytes());
			}
			_ctx.write(msg).addListener(ChannelFutureListener.CLOSE);
			_ctx.flush();
		}
	}
}
